import {
  baseURL,
  timeout
} from './config.js'

function _modifyPostParam(obj) {
  let query = '';
  let name, value, fullSubName, subName, subValue, innerObj, i;
  for (name in obj) {
    value = obj[name];
    if (value instanceof Array) {
      for (i = 0; i < value.length; ++i) {
        subValue = value[i];
        fullSubName = name + '[' + i + ']';
        innerObj = {};
        innerObj[fullSubName] = subValue;
        query += this._modifyPostParam(innerObj) + '&';
      }
    } else if (value instanceof Object) {
      for (subName in value) {
        subValue = value[subName];
        fullSubName = name + '[' + subName + ']';
        innerObj = {};
        innerObj[fullSubName] = subValue;
        query += this._modifyPostParam(innerObj) + '&';
      }
    } else if (value !== undefined && value !== null) {
      query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }
  }
  return query.length ? query.substr(0, query.length - 1) : query;
}
function request(options) {
  let reg = RegExp(/http/),
  header= options.header,
    data = options.data || {};
  !options.showOnload ? wx.showLoading({ title: '请求中...' }) : ''; //不传默认显示数据加载中
  if (wx.getStorageSync('access_token')){
    data.access_token = wx.getStorageSync('access_token')
  }
  if (options.method) {
    if (options.method == 'POST') {
      data = options.type==1?data:_modifyPostParam(data);
      header = header || {
        'content-type': 'application/x-www-form-urlencoded;'
      }
    }
  } else {
    options.method = 'get'
  }
  options.method = options.method.toUpperCase(); //转小写
  return new Promise((resolve, reject) => {
    wx.request({
      url: (reg.test(options.url) ? '' : baseURL) + options.url,
      timeout: timeout,
      data: data,
      method: options.method,
      header: header || {'content-type': 'application/json'},
      success: function(res) {
        if(res.code==500){
          wx.navigateBack({})
        } else {
          resolve(res.data, options.method)
        }
      },
      fail: reject,
      complete: res => {
        !options.showOnload ? wx.hideLoading() : '';
      }
    })
  })
}

export default request;

